(function ($, window, document,undefined) {

    captcha = {
        /**
         * 校验状态
         */
        checkFlag: false
        /**
         * 初始化验证码
         * @param containerElem
         * @param captchaType
         */
        ,init: function init(containerElem ,captchaType ,url ,param ,width ,height) {
            if("image" == captchaType){
                initImageCaptcha(containerElem ,captchaType ,url ,param  ,width ,height )
            }else if("jigsaw" == captchaType){
                initJigsawCaptcha(containerElem ,captchaType ,url ,param  ,width ,height)
            }
        }
        ,checkFlag: function () {
            return this.checkFlag;
        }
    };


    /**
     * 初始化图片验证码
     * @param containerElem
     */
    function initImageCaptcha(containerElem,captchaType ,url , param ,width ,height) {
        $.ajax({
            type : "post",
            contentType: "application/json;charset=UTF-8",
            url : url,
            data :JSON.stringify(param),
            success:function(res){
                if(res.status){
                    var $container = $(containerElem);
                    $container.children().remove();
                    var widthAttr = width ? 'width="'+width+'"' : '';
                    var heightAttr = height ? 'height="'+height+'"' : '';
                    var $showHtml = $('<img src="'+res.data.base64+'" alt="captcha" title="点击切换" '+widthAttr + ' ' + heightAttr +' >')
                    $container.append($showHtml);
                    $showHtml.click(function () {
                        initImageCaptcha(containerElem ,captchaType ,url ,param ,width ,height);
                    })

                    var $tokenHtml = $('<input type="hidden" name="token" value="'+res.data.token+'">')
                    $container.append($tokenHtml);

                    $container.removeClass('hide').show();

                    //设置校验状态
                    captcha.checkFlag = true;
                }else{
                    system.error("初始化图片验证码功能失败:" + res.msg)
                }
            },
            fail: function(err) {
                console.log(err);
            }
        })
    }

    /**
     * 初始化拼图验证码
     * @param containerElem
     */
    function initJigsawCaptcha(containerElem ,captchaType ,url ,param ,width ,height) {
        var getResult;
        JigsawCaptcha($(containerElem) ,{
            width: width
            ,height: height
            ,renderDataCall: function () {
                var result = {
                    originalImageBase64: '原图'
                    ,jigsawImageBase64: '拼图'
                    ,jigsawY: 0
                }
                $.ajax({
                    async: false ,
                    type : "post",
                    url : url,
                    data : param,
                    success:function(res){
                        if(res.status){
                            result.originalImageBase64 = res.data.originalImageBase64;
                            result.jigsawImageBase64 = res.data.jigsawImageBase64;
                            result.jigsawY = res.data.jigsawY;
                            getResult = res;
                        }else{
                            system.error("初始化拼图验证码功能失败:" + res.msg)
                        }
                    },
                    fail: function(err) {
                        console.log(err);
                    }
                })
                return result;
            }
            ,checkCall: function (x ,y) {
                var checkParam = {
                    token: getResult.data.token
                    ,x : x
                    ,y : y
                }
                $.ajax({
                    async: false ,
                    type : "post",
                    url : system.contextPath + "/captcha/"+captchaType+"/verify",
                    data : checkParam,
                    success:function(res){
                        if(res.status){
                            captcha.checkFlag = res.data.success;
                            if(res.data.success){
                                //二次校验参数
                                var $tokenHtml = $('<input type="hidden" name="token" value="'+res.data.token+'">')
                                $(containerElem).append($tokenHtml);
                                system.success("校验通过");
                                return;
                            }
                        }
                        system.error("认证失败，请重试：" + res.msg);
                        captcha.checkFlag = false;
                    },
                    fail: function(res) {
                        system.error("认证失败，请重试：" + res.msg);
                        captcha.checkFlag = false;
                    }
                })
                return captcha.checkFlag;
            }
        })
    }

    /**
     * 拼图验证码
     * @param containerElem html数据展示容器
     * @param renderDataCall 渲染数据回调
     * @param checkCall 验证码校验回调
     * @returns {JigsawCaptcha}
     * @constructor
     */
    var JigsawCaptcha = function(containerElem ,options){
        // 判断是用函数创建的还是用new创建的。这样我们就可以通过MaskShare("dom") 或 new MaskShare("dom")来使用这个插件了
        if (!(this instanceof JigsawCaptcha)) return new JigsawCaptcha(containerElem, options);
        //html展示效果的存储容器
        this.container = $(containerElem);
        // 操作参数
        this.options = this.extend({
            width: 400
            ,height: 200
            /**
             * 渲染数据回调
             * @returns {{originalImageBase64: string, jigsawImageBase64: string ，jigsawY: int}}
             */
            ,renderDataCall : function () {
                return {
                    originalImageBase64: '原图'
                    ,jigsawImageBase64: '拼图'
                    ,jigsawY: '拼图相对原图的y高度'
                }
            }
            /**
             * 验证码校验回调
             * @param x 拼图的x坐标
             * @param y 拼图的y坐标
             * @returns true | false 验证成功或失败
             */
            ,checkCall: function (x ,y) {
                return false
            }
        }, options);

        this.init();
    }

    JigsawCaptcha.prototype = {
        /**
         * 校验结果
         */
        checkResult: false
        /**
         * 为容器初始化展示模块
         */
        ,init: function () {
            this.reset()
        }
        ,extend: function (obj, obj2) {
            for (var k in obj2) {
                obj[k] = obj2[k];
            }
            return obj;
        }
        ,reset: function () {
            this.container.children().remove();
            var renderData = this.options.renderDataCall();
            //容器
            var $_container = $('<div style="width: '+this.options.width+'px;height: '+(this.options.height + 50)+'px;"></div>');
            this.container.append($_container);
            //图片容器
            var $_imageContainer = $('<div style="height: '+this.options.height+'px; border: 1px solid #ccc;position: relative"></div>');
            $_container.append($_imageContainer);
            //原图
            var $_originalHtml = $('<img src="data:image/jpeg;base64,'+renderData.originalImageBase64+'" width="100%" height="100%">');
            $_imageContainer.append($_originalHtml);
            //拼图
            var $_jipsawHtml = $(' <div style="position: absolute;top: '+renderData.jigsawY+'px;">\n' +
                '                            <img src="data:image/jpeg;base64,'+renderData.jigsawImageBase64+'" width="100%" height="100%">\n' +
                '                  </div>');
            $_imageContainer.append($_jipsawHtml);
            //滑动功能容器
            var $_moveFnContainer = $('<div style="margin-top: 20px;width: '+this.options.width+'px;height: 20px;position: relative;border-radius: 20px;\n' +
                '                    background-color: #c3c3c3;text-align: center;color:white;">\n' +
                '                 </div>')
            $_container.append($_moveFnContainer);
            //滑动功能
            var $_moveFnHtml = $('<div style="position: absolute;left: 0;top: -12px;border: 1px solid #d0e9c6;width: 40px;height: 40px;\n' +
                '                        border-radius: 40px;background-color: #00F7DE"></div>\n' +
                '                        滑动图片完成校验\n' );
            $_moveFnContainer.append($_moveFnHtml);

            var _this = this;
            // --- 功能添加
            // 直接滑动拼图
            system.setToRemovable($_jipsawHtml ,$_imageContainer ,{
                moveCall: function (x ,y) {
                    x ? $_moveFnHtml.css("left" ,x) : '';
                }
                ,
                overCall: function (x ,y) {
                    var res = _this.options.checkCall(x ,renderData.jigsawY)
                    if(!res){
                        //alter
                        $_moveFnHtml.css("left" ,0);
                        $_jipsawHtml.css("left" ,0);
                    }
                }
                ,isMoveY: false
            })

            //滑动条
            system.setToRemovable($_moveFnHtml ,$_moveFnContainer ,{
                moveCall: function (x ,y) {
                    x ? $_jipsawHtml.css("left" ,x) : '';
                }
                ,overCall: function (x ,y) {
                    var res = _this.options.checkCall(x ,renderData.jigsawY);
                    if(!res){
                        //alter
                        $_moveFnHtml.css("left" ,0);
                        $_jipsawHtml.css("left" ,0);
                    }
                }
                ,isMoveY: false
            })
        }
    }

})(jQuery, window, document)